<?php


namespace App\Kuafu\User\Controller\Internal;


use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Sms\Enum\SmsCodeEnum;
use App\Kuafu\Sms\Service\SmsService;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserService;
use Illuminate\Http\Request;

class LoginController extends BaseController
{

    /**
     * 飞书登录
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse|mixed|string
     * @throws \App\Kuafu\User\Exceptions\AuthException
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function login(Request $request)
    {
        $user = UserService::getUserValue('mobile', $request->mobile);
        if (!$user) {
            return $this->fail(UserCodeEnum::ERR_USER_NOT_EXIST,
                UserCodeEnum::CODE_TEXT[UserCodeEnum::ERR_USER_NOT_EXIST]);
        }
        if (!$user['feishuUserId']) {
            $data = ['feishuUserId' => $request['userId']];
            UserService::setUserFieldByUserId($user['id'], $data);
        }
        $token = AuthService::mobileLogin($request->mobile, UserCodeEnum::WEB_TYPE, 1, (string)$request->get('ip'));
        return $this->success(['token' => $token, 'userInfo' => $user]);
    }

    /**
     * 校验验证码--kms手机号登录-审核用
     * @param Request $request
     */
    public function verifyCode(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required|string',
            'code'   => 'required|string',
        ]);
        $resData = [
            'code' => 200,
            'msg'  => '',
        ];
        try {
            SmsService::verifyCode($request->mobile, $request->code, SmsService::CODE_TYPE_MOBILE_LOGIN);
        } catch (\Exception $e) {
            $resData['code'] = SmsCodeEnum::SMS_CODE_EXPIRE;
            $resData['msg']  = '验证码已失效，请重新获取';
        }
        return $this->success($resData);
    }
}
